import { defineStore, acceptHMRUpdate } from 'pinia'
import { useRoute, useRouter } from 'vue-router'

// const route = useRoute()
// const router = useRouter()
const asideCollapse = localStorage.getItem('VITE_VUE_TS_TEMPLATE-ASIDE_STATUS') === 'true' ? true : false

export const useMainStore = defineStore({
  id: 'useMain',
  state: () => ({
    name: 'elewen',
    age: 12,
    openedList: [],
    aliveList: [],
    asideCollapse,
    firstTabName: 'Home',
    isFullscreen: false,
  }),
  getters: {},
  actions: {
    /**
     *
     * @param mode
     * @param route
     * @param routeName
     */
    updateOpenedList ({ mode, route = {}, routeName= '' }) {
      switch (mode) {
        case 'add': {
          const { fullPath, name, query, meta: { keepAlive, hideTab } } = route

          keepAlive && this.updateAliveList({
            mode: 'add',
            name,
          })

          if (!hideTab) {
            const tabIndex = this.openedList.findIndex(_route => _route.name === name)
            // 当前导航的路由不在tabs中, 则向tabs追加一条记录; 如果是Home, 则要追加到最前面
            if (tabIndex === -1) {
              // name !== this.firstTabName ? this.openedList.push(toRoute) : this.openedList.unshift(toRoute)
              this.openedList[name !== this.firstTabName ? 'push' : 'unshift'](route)
              this.openedList = [...new Set(this.openedList)]
            }
          }
        }
        break;
        case 'remove': {
          console.log(routeName)
          const tabIndex = this.openedList.findIndex(_route => _route.name === routeName)
          if (tabIndex !== -1) {
            const removedList = this.openedList.splice(tabIndex, 1)
            const { fullPath, name, query, meta: { keepAlive } } = removedList[0]
            if (keepAlive) {
              this.updateAliveList({
                mode: 'remove',
                name,
              })
            }
          }
        }
        break;
        case 'clear':
          this.openedList = []
          break;
        default:
          break;
      }
    },
    updateAliveList ({ mode, name }) {
      switch (mode) {
        case 'add':
          this.aliveList.push(name)
          this.aliveList = [...new Set(this.aliveList)]
          break;
        case 'remove':
          const ind = this.aliveList.findIndex(_name => _name === name)
          ind !== -1 && this.aliveList.splice(ind, 1)
          break;
        case 'clear':
          this.aliveList = []
          break;
        default:
          break;
      }
    },
    toggleAsideStatus () {
      this.asideCollapse = !this.asideCollapse
      localStorage.setItem('VITE_VUE_TS_TEMPLATE-ASIDE_STATUS', this.asideCollapse)
    },
  },
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useMainStore, import.meta.hot))
}
